package com.sz.lk.wingsystem.ui;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.sz.lk.wingsystem.MainApp;
import com.sz.lk.wingsystem.R;
import com.sz.lk.wingsystem.bean.ManualResult;
import com.sz.lk.wingsystem.bean.WeightResult;
import com.sz.lk.wingsystem.inter.MakePariBlueToothListener;
import com.sz.lk.wingsystem.madapter.MyListAdapter;
import com.sz.lk.wingsystem.mbluetooth.ClientThread;
import com.sz.lk.wingsystem.mbluetooth.ClsUtils;
import com.sz.lk.wingsystem.mbluetooth.Params;
import com.sz.lk.wingsystem.mbluetooth.ServerThread;
import com.sz.lk.wingsystem.mutils.CrashHandler;
import com.sz.lk.wingsystem.mutils.SaveUtils;
import com.sz.lk.wingsystem.mutils.ToastUtils;
import com.sz.lk.wingsystem.mutils.log.AppLogger;
import com.sz.lk.wingsystem.mvp.BaseActivity;
import com.sz.lk.wingsystem.mvp.ModelPath;
import com.sz.lk.wingsystem.mvp.contract.WeighContract;
import com.sz.lk.wingsystem.mvp.presenter.WeighPresenter;
import com.sz.lk.wingsystem.widgets.ClearableEditText;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sz.lk.wingsystem.mbluetooth.Params.MSG_DATA;

/**
 * @author : liuke
 * e-mail : 1012459343@qq.com
 * date   : 2020/12/7
 * desc   :
 * version: 1.0
 */
public class WeighPage extends BaseActivity<WeighPresenter> implements WeighContract.view {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.cz_bt)
    Button czBt;
    @BindView(R.id.c_code)
    ClearableEditText cCode;
    @BindView(R.id.c_weigh)
    ClearableEditText cWeigh;
    @BindView(R.id.c_volume)
    ClearableEditText cVolume;
    @BindView(R.id.c_length)
    ClearableEditText cLength;
    @BindView(R.id.c_width)
    ClearableEditText cWidth;
    @BindView(R.id.c_height)
    ClearableEditText cHeight;
    @BindView(R.id.code_searchcc)
    ClearableEditText codeSearchcc;
    @BindView(R.id.btcon)
    Button btcon;
    @BindView(R.id.device_list_view)
    RecyclerView deviceListView;

    private String weightdata = "";
    MyBtReceiver btReceiver;
    IntentFilter intentFilter;
    List<BluetoothDevice> deviceList = new ArrayList<>();
    private final String ACTIONFILTER = "android.bluetooth.device.action.PAIRING_REQUEST";
    //此处为你要连接的蓝牙设备的初始密钥，一般为1234或0000
    String pin = "1234";
    ClientThread clientThread;
    ServerThread serverThread;
    private Handler lunxun = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Get_WeighCartonNo(set("ss", "B"));
          /*  try {
                Log.e("yuyuy", "jkjljlj");
                if (!_socket.isConnected()) {
                    title.setText("称重（蓝牙已断开）");
                    btcon.setText("连接蓝牙设备");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            lunxun.postDelayed(runnable, 1000);*/
        }
    };
    Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case Params.MSG_SERVER_REV_NEW:
                    String newMsgFromClient = msg.obj.toString();
                    break;
                case Params.MSG_CLIENT_REV_NEW:
                    String newMsgFromServer = msg.obj.toString();
                    weightdata = newMsgFromServer;
                    Log.e("sssss", weightdata);
                    break;
                case Params.MSG_WRITE_DATA:
                    String dataSend = msg.obj.toString();
                    break;
                case Params.CONNECT_FAILE:
                    Log.e("TAG", "--------- connect faile");
                    ToastUtils.show("连接失败");
                    break;
                case MSG_DATA:
                    Log.e("TAG", "--------- connect faile");
                    Toast.makeText(WeighPage.this, msg.getData().getString("data"), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    MyListAdapter listAdapter;

    //宏定义查询设备句柄
    private final static int REQUEST_CONNECT_DEVICE = 1;
    private String tempcode = "";
    //获取本地蓝牙适配器，即蓝牙设备
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
    //蓝牙通信socket
    private BluetoothSocket _socket = null;
    boolean bRun = true;
    boolean bThread = false;
    //输入流，用来接收蓝牙数据
    private InputStream is;
    BluetoothDevice _device = null;     //蓝牙设备
    //消息处理队列
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //Log.e("ssss", set("dd", "B"));
            title.setText("称重（蓝牙已断开）");
            btcon.setText("连接");
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 6.0) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    Params.MY_PERMISSION_REQUEST_CONSTANT);
        }
        _bluetooth = BluetoothAdapter.getDefaultAdapter();
        if (_bluetooth == null) {
            Log.e("TAG", "--------------- 不支持蓝牙");
            finish();
        }
    }

    @Override
    protected void initEventAndData() {
        CrashHandler catchHandler = CrashHandler.getInstance();
        catchHandler.init(this);
        codeSearchcc.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    Log.i("---", "搜索操作执行");
                    ToastUtils.show(codeSearchcc.getText().toString().trim());
                    tempcode = codeSearchcc.getText().toString().trim();
                    codeSearchcc.setText("");
                    cCode.setText(tempcode);
                    if (null == _socket) {
                        ToastUtils.show("蓝牙未连接，请连接蓝牙！");
                    } else {
                        try {
                            bRun = false;
                            Thread.sleep(500);

                            is.close();
                            _socket.close();
                            _socket = null;

                            /*btcon.setText("连接");
                            title.setText("称重（蓝牙已断开）");
                            ToastUtils.show("蓝牙已断开");*/
                        } catch (IOException ignored) {
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (NullPointerException w) {
                            w.printStackTrace();
                        }
                        // 得到蓝牙设备句柄
                        String mac = (String) SaveUtils.getInstance().get(WeighPage.this,"mac","00.00.00.00");
                        _device = _bluetooth.getRemoteDevice(mac);

                        // 用服务号得到socket
                        try {
                            _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(Params.UUID));
                        } catch (IOException e) {
                            Toast.makeText(WeighPage.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                        //连接socket
                        try {
                            _socket.connect();
                            Toast.makeText(WeighPage.this, "连接" + _device.getName() + "成功！", Toast.LENGTH_SHORT).show();
                            title.setText("称重（蓝牙已连接）");
                            btcon.setText("断开蓝牙");
                        } catch (IOException e) {
                            try {
                                Toast.makeText(WeighPage.this, "连接失败！", Toast.LENGTH_SHORT).show();
                                _socket.close();
                                _socket = null;
                            } catch (IOException ee) {
                                Toast.makeText(WeighPage.this, "连接失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        //打开接收线程
                        try {
                            is = _socket.getInputStream();   //得到蓝牙数据输入流
                        } catch (IOException e) {
                            Toast.makeText(WeighPage.this, "接收数据失败！", Toast.LENGTH_SHORT).show();
                        }
                        if (bThread == false) {
                            readThread.start();
                            bThread = true;
                        } else {
                            bRun = true;
                        }
                        lunxun.postDelayed(runnable, 500);
                    }
                }
                return true;
            }
        });
        title.setText("称重");
        // 设置设备可以被搜索
        new Thread() {
            @Override
            public void run() {
                if (!_bluetooth.isEnabled()) {
                    _bluetooth.enable();
                }
            }
        }.start();
        /*final ExecutorService threadExecutor = Executors.newFixedThreadPool(1);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        // 设置布局管理器
        deviceListView.setLayoutManager(layoutManager);
        listAdapter = new MyListAdapter(deviceList, this);
        deviceListView.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
        listAdapter.setOnItemClickListener((adapter, view, position) -> {
            //    关闭服务器监听
            Log.e("TAG", "accept:点击位置 ：" + position);
            itmClikPostion(position, threadExecutor);
        });
        listAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.device_pair) {
                try {
                    //通过工具类ClsUtils,调用createBond方法
                    BluetoothDevice btDevice = deviceList.get(position);
                    ClsUtils.createBond(btDevice.getClass(), btDevice);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });*/
    }

    @Override
    protected WeighPresenter initPresenter() {
        return new WeighPresenter();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_weigh_page;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }


    @OnClick({R.id.back, R.id.cz_bt, R.id.btcon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                //finish();
                //关闭连接socket
                try {
                    bRun = false;
                    Thread.sleep(500);

                    is.close();
                    _socket.close();
                    _socket = null;

                    btcon.setText("连接");
                    title.setText("称重（蓝牙已断开）");
                    ToastUtils.show("蓝牙已断开");
                } catch (IOException ignored) {
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (NullPointerException w) {
                    w.printStackTrace();
                }
                startActivity(new Intent(this, MenuPage.class));
                break;
            case R.id.cz_bt:
                String code = Objects.requireNonNull(cCode.getText()).toString().trim();
                double weight = Double.parseDouble(Objects.requireNonNull(cWeigh.getText()).toString().trim());
                double volume = Double.parseDouble(Objects.requireNonNull(cVolume.getText()).toString().trim());
                double length = Double.parseDouble(Objects.requireNonNull(cLength.getText()).toString().trim());
                double width = Double.parseDouble(Objects.requireNonNull(cWidth.getText()).toString().trim());
                double height = Double.parseDouble(Objects.requireNonNull(cHeight.getText()).toString().trim());
                //mPresenter.Get_ManualNewReportInfo(code, weight, volume, length, width, height);
                Get_ManualNewReportInfo(code, weight, volume, length, width, height);
                break;
            case R.id.btcon:
                connect_bt();
                break;
            default:
                break;
        }
    }

    public void connect_bt() {
        if (_bluetooth.isEnabled() == false) {  //如果蓝牙服务不可用则提示
            Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();
            return;
        }
        //如未连接设备则打开DeviceListActivity进行设备搜索
        if (_socket == null) {
            Intent serverIntent = new Intent(this, DeviceListActivity.class); //跳转程序设置
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);  //设置返回宏定义
        } else {
            //关闭连接socket
            try {
                bRun = false;
                Thread.sleep(2000);

                is.close();
                _socket.close();
                _socket = null;
                title.setText("称重（蓝牙已断开）");
                btcon.setText("连接");
            } catch (IOException e) {
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return;
    }

    /**
     * isSucceed : true
     * errorCode : 0
     * opTime : 2020-12-06 09:58:05
     * remark : null
     * result : {"data":{"code":null,"weight":32.05,"volume":0.023,"length":0,"width":0,"height":0}}
     */
    @Override
    public void onWeighCartonNoSuccess(WeightResult bean) {
        AppLogger.e(new Gson().toJson(bean));
        if (bean.isIsSucceed()) {
            cCode.setText(tempcode);
            cWeigh.setText(bean.getResult().getData().getWeight() + "");
            cVolume.setText(bean.getResult().getData().getVolume() + "");
            cLength.setText(bean.getResult().getData().getLength() + "");
            cWidth.setText(bean.getResult().getData().getWidth() + "");
            cHeight.setText(bean.getResult().getData().getHeight() + "");
        } else {
            ToastUtils.show(bean.getRemark().toString());
        }
    }

    @Override
    public void onManualNewReportInfoSuccess(ManualResult bean) {
        if (bean.isIsSucceed()) {
            ToastUtils.show("称重上传成功");
        } else {
            ToastUtils.show(bean.getRemark().toString());
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void showWaitingDialog(String tip) {

    }

    @Override
    public void hideWaitingDialog() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        if (requestCode == Params.MY_PERMISSION_REQUEST_CONSTANT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 运行时权限已授权
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 蓝牙未打开，询问打开
        /*if (!bluetoothAdapter.isEnabled()) {
            Intent turnOnBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOnBtIntent, Params.REQUEST_ENABLE_BT);
        } else {
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();
            }
            showBondDevice();
            if (deviceList.size() == 0) {
                bluetoothAdapter.startDiscovery();
            }
        }
        intentFilter = new IntentFilter();
        btReceiver = new MyBtReceiver();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(ACTIONFILTER);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(btReceiver, intentFilter);
        btReceiver.SetPairlistener(new MakePariBlueToothListener() {
            @Override
            public void whilePari(BluetoothDevice device) {

            }

            @Override
            public void pairingSuccess(BluetoothDevice device) {
                listAdapter.notifyDataSetChanged();
            }

            @Override
            public void cancelPari(BluetoothDevice device) {

            }
        });

        // 蓝牙已开启
        if (bluetoothAdapter.isEnabled()) {
            showBondDevice();
            // 默认开启服务线程监听
            if (serverThread != null) {
                serverThread.cancel();
            }
            Log.e("TAG", "-------------- new server thread");
            serverThread = new ServerThread(bluetoothAdapter, uiHandler);
            new Thread(serverThread).start();
        }*/
    }


    /**
     * 广播接受器
     */
    private class MyBtReceiver extends BroadcastReceiver {
        MakePariBlueToothListener mMakePariListener;

        public void SetPairlistener(MakePariBlueToothListener makePariBlueToothListener) {
            this.mMakePariListener = makePariBlueToothListener;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice btDevice = null;  //创建一个蓝牙device对象
            // 从Intent中获取设备对象
            btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                ToastUtils.show("开始搜索 ...");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                ToastUtils.show("搜索结束");
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (isNewDevice(device)) {
                    deviceList.add(device);
                    listAdapter.notifyDataSetChanged();
                    Log.e("TAG", "---------------- " + device.getName());
                }
            } else if (ACTIONFILTER.equals(action)) {
                Log.e("action2=", action);
                Log.e("here", "btDevice.getName()");
                try {
                    //1.确认配对
                    ClsUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);
                    //2.终止有序广播
                    Log.i("order...", "isOrderedBroadcast:" + isOrderedBroadcast() + ",isInitialStickyBroadcast:" + isInitialStickyBroadcast());
                    abortBroadcast();//如果没有将广播终止，则会出现一个一闪而过的配对框。
                    //3.调用setPin方法进行配对...
                    boolean ret = ClsUtils.setPin(btDevice.getClass(), btDevice, pin);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {

                switch (btDevice.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:// 正在配对
                        mMakePariListener.whilePari(btDevice);
                        break;
                    case BluetoothDevice.BOND_BONDED:// 配对结束
                        mMakePariListener.pairingSuccess(btDevice);
                        break;
                    case BluetoothDevice.BOND_NONE:// 取消配对/未配对
                        mMakePariListener.cancelPari(btDevice);
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 判断搜索的设备是新蓝牙设备，且不重复
     *
     * @param device
     * @return
     */
    private boolean isNewDevice(BluetoothDevice device) {
        boolean repeatFlag = false;
        for (BluetoothDevice d :
                deviceList) {
            if (d.getAddress().equals(device.getAddress())) {
                repeatFlag = true;
            }
        }
        //不是已绑定状态，且列表中不重复
        return device.getBondState() != BluetoothDevice.BOND_BONDED && !repeatFlag;
    }

    /**
     * 用户打开蓝牙后，显示已绑定的设备列表
     */
   /* private void showBondDevice() {
        deviceList.clear();
        Set<BluetoothDevice> tmp = bluetoothAdapter.getBondedDevices();
        for (BluetoothDevice d :
                tmp) {
            deviceList.add(d);
        }
        listAdapter.notifyDataSetChanged();
    }*/

   /* private void itmClikPostion(int position, ExecutorService threadExecutor) {

        if (serverThread != null) {
            serverThread.cancel();
            serverThread = null;
            Log.e("TAG", "---------------client item click , cancel server thread ," +
                    "server thread is null");
        }
        final BluetoothDevice device1 = deviceList.get(position);
        // 开启客户端线程，连接点击的远程设备
        clientThread = new ClientThread(bluetoothAdapter, device1, uiHandler);
        threadExecutor.execute(clientThread);
//                new Thread(clientThread).start();
        clientThread.SetConnectBack(new ClientThread.ConnectBack() {
            @Override
            public void connectsuccess(BluetoothDevice device) {
                // 通知 ui 连接的服务器端设备
                Message message = new Message();
                message.what = Params.MSG_CONNECT_TO_SERVER;
                message.obj = device;
                uiHandler.sendMessage(message);
            }

            @Override
            public void connectfaile(BluetoothDevice device) {
                runOnUiThread(() -> ToastUtils.show("连接失败,请检查服务端是否打开。"));
            }

            @Override
            public void connecting(BluetoothDevice device) {
                runOnUiThread(() -> ToastUtils.show("请稍等，正在连接中。"));
            }
        });
    }*/
    @Override
    protected void onDestroy() {
        super.onDestroy();
       /* try {
            clientThread.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        unregisterReceiver(btReceiver);*/
//关闭连接socket
        if (_socket != null) {
            try {
                _socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //	_bluetooth.disable();  //关闭蓝牙服务
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       /* if (requestCode == Params.REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                showBondDevice();
            }
        }*/
        if (requestCode == REQUEST_CONNECT_DEVICE) {     //连接结果，由DeviceListActivity设置返回
            // 响应返回结果
            if (resultCode == Activity.RESULT_OK) {   //连接成功，由DeviceListActivity设置返回
                // MAC地址，由DeviceListActivity设置返回
                String address = data.getExtras()
                        .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // 得到蓝牙设备句柄
                _device = _bluetooth.getRemoteDevice(address);
                SaveUtils.getInstance().save(this,"mac",address);
                // 用服务号得到socket
                try {
                    _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(Params.UUID));
                } catch (IOException e) {
                    Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                }
                //连接socket
                try {
                    _socket.connect();
                    Toast.makeText(this, "连接" + _device.getName() + "成功！", Toast.LENGTH_SHORT).show();
                    title.setText("称重（蓝牙已连接）");
                    btcon.setText("断开蓝牙");
                } catch (IOException e) {
                    try {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                        _socket.close();
                        _socket = null;
                    } catch (IOException ee) {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                    }

                    return;
                }

                //打开接收线程
                try {
                    is = _socket.getInputStream();   //得到蓝牙数据输入流
                } catch (IOException e) {
                    Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (bThread == false) {
                    readThread.start();
                    bThread = true;
                } else {
                    bRun = true;
                }
            }
        }
    }

    /**
     * 称重解析
     *
     * @param weightStr
     */
    public void Get_WeighCartonNo(String weightStr) {
        Map<String, Object> merchant = new HashMap<>();
        merchant.put("weightStr", weightStr);
        JSONObject jsonObject = new JSONObject(merchant);
        AppLogger.i("解析请求数据：" + jsonObject.toString());
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, ModelPath.baseUrl_NO_Splite + "Weight/WeighCartonNo", jsonObject,
                response -> {
                    String a = response.toString();
                    Log.e("hjhjhjhjh", a);
                    AppLogger.i("解析请求返回数据：" + a);
                    onWeighCartonNoSuccess(new Gson().fromJson(a, WeightResult.class));
                }, error -> {
            AppLogger.i("解析请求异常：" + error.getMessage());
            ToastUtils.show(error.getMessage());
        }) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };
        MainApp.mQueue.add(jsonRequest);
    }

    public void Get_ManualNewReportInfo(String code, double weight, double volume, double length, double width, double height) {
        Map<String, Object> merchant = new HashMap<>();
        merchant.put("code", code);
        merchant.put("weight", weight);
        merchant.put("volume", volume);
        merchant.put("length", length);
        merchant.put("width", width);
        merchant.put("height", height);
        JSONObject jsonObject = new JSONObject(merchant);
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, ModelPath.baseUrl_NO_Splite + "Weight/ManualNewReportInfo", jsonObject,
                response -> {
                    String a = response.toString();
                    onManualNewReportInfoSuccess(new Gson().fromJson(a, ManualResult.class));
                }, error -> {
            ToastUtils.show(error.getMessage());
        }) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };
        MainApp.mQueue.add(jsonRequest);
    }

    //接收数据线程
    Thread readThread = new Thread() {

        @Override
        public void run() {
            int num = 0;
            byte[] buffer = new byte[1024];
            byte[] buffer_new = new byte[1024];
            int i = 0;
            int n = 0;
            bRun = true;
            //接收线程
            while (true) {
                try {
                    while (is.available() == 0) {
                        Log.e("sasasa","ooooooo");
                        while (bRun == false) {
                        }
                    }
                    while (true) {
                        if (!bThread)//跳出循环
                        {
                            return;
                        }

                        num = is.read(buffer);         //读入数据
                        n = 0;
                        for (i = 0; i < num; i++) {
                            if ((buffer[i] == 0x0d) && (buffer[i + 1] == 0x0a)) {
                                buffer_new[n] = 0x0a;
                                i++;
                            } else {
                                buffer_new[n] = buffer[i];
                            }
                            n++;
                        }
                        String s = new String(buffer_new, 0, n);
                        Log.e("hu",s);
                        set(s, "A");
                        //weightdata = s;   //写入接收缓存
                        if (is.available() == 0) {
                            break;  //短时间没有数据才跳出进行显示
                        }
                    }
                    //发送显示消息，进行显示刷新
                    //handler.sendMessage(handler.obtainMessage());
                } catch (IOException e) {
                    Log.e("sasa","ppppp");
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public synchronized String set(String s, String flag) {
        if (flag.equals("A")) {
            weightdata = s;
        }
        return weightdata;
    }
}